package com.intct.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.java.utils.ParameterTool;

import java.io.IOException;

/**
 * @author gufg
 * @since 2025-09-19 15:05
 */
public class LettuceUtil {
    public static StatefulRedisConnection<String,String> getRedisAsyncConnection() {
        // 从工程中resoucres路径读取配置文件
        ParameterTool parameterTool = null;
        try {
            parameterTool = ParameterTool.fromPropertiesFile(LettuceUtil.class.getResource("/intct.properties").getFile());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String hosts = parameterTool.get("redis.host", "node1");
        String port = parameterTool.get("redis.port", "16379");
        String password = parameterTool.get("redis.password", "123456");

        RedisURI uri = RedisURI.builder().withHost(hosts).withPort(Integer.parseInt(port)).withPassword(password).build();
//        RedisURI uri = RedisURI.builder().withHost("cdh-node").withPort(16379).withPassword("Test_090110").build();
        RedisClient redisClient = RedisClient.create(uri);
        return redisClient.connect();
    }

    //关闭异步操作Redis的连接对象
    public static void closeRedisAsyncConnection(StatefulRedisConnection<String,String> asyncRedisConn){
        // System.out.println("~~~关闭异步操作Redis的客户端~~~");
        if(asyncRedisConn != null && asyncRedisConn.isOpen()){
            asyncRedisConn.close();
        }
    }

    //以异步的方式从Redis中取数据
    public static JSONObject readDimAsync(StatefulRedisConnection<String,String> asyncRedisConn, String id){
        RedisAsyncCommands<String, String> asyncCommands = asyncRedisConn.async();
        try {
            String dimJsonStr = asyncCommands.get(id).get();
            if(StringUtils.isNotEmpty(dimJsonStr)){
                JSONObject dimJsonObj = JSON.parseObject(dimJsonStr);
                return dimJsonObj;
            }
        } catch (Exception e) {
            //throw new RuntimeException(e);
        }
        return null;
    }
    //以异步的方式向Redis中放数据
    public static void writeDimAsync(StatefulRedisConnection<String,String> asyncRedisConn,
                                     String id,JSONObject dimJsonObj){
        RedisAsyncCommands<String, String> asyncCommands = asyncRedisConn.async();
        String key = id;
        asyncCommands.setex(key,24*60*60,dimJsonObj.toJSONString());
    }

}
